#pragma once
#include <iostream>
#include <string>
#include "Reactor.hpp"
#include "InitAddr.hpp"
#include "Log.hpp"
#include "Connection.hpp"
#include "comm.hpp"
#include "HandlerEvent.hpp"
using namespace std;


class Accepter {
    public :
    static void Accept(Connection* conn) {
        while (true) {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // cout << "阻塞" << endl;
            int newsocket = accept(conn->SockFd(), (sockaddr*)&peer, &len);
            // cout << "不阻塞" << endl;
            // 将newsocket设置成非阻塞
            if (newsocket > 0) {
                SetNonBlock(newsocket);
                Connection* normal_conn = ConnectionFactory::BuildNormalConnection(newsocket, EPOLLIN | EPOLLET, conn->_R,\
                 HandlerEvent::recver, HandlerEvent::sender, HandlerEvent::excepter);
                normal_conn->SetAddr(peer);
                conn->_R->AddConnection(normal_conn);
                lg.LogMessage(Info, "get a new link client info: %s", normal_conn->Get_Info().c_str());
            } else {
                if (errno == EAGAIN) { // 说明已经吧本轮数据读完
                    break;
                } else if (errno == EINTR) { // 表示被信号中断了
                    continue;
                } else {
                    lg.LogMessage(Warning, "get a new link error, errno: %d, error string: %s", errno, strerror(errno));
                    break;
                }
            }

        }

    }
};